const webpack = require("webpack");
const path = require("path");
const fs = require('fs');

const dir = require("./dir");

const pathToName = require(path.join(dir.frameworkCommonDir, 'driver')).pathToName;
const resolve = require("./driver").resolve;

module.exports = async (source_path) => {
    let config_file = path.join(resolve(source_path), 'config.js');
    let app_file = path.join(resolve(source_path), 'app.js');

    if (!fs.existsSync(config_file)) {
        console.log(`未找到文件：${config_file}`)
        return;
    }

    const config = require(config_file);

    let app = Object.assign({}, config);

    app.plugs = app.plugs || {};
    app.beans = {};
    app.tags = {};

    if (config.plugs)
        for (let name in config.plugs) {
            let plug = config.plugs[name];
            app.plugs[name] = plug;

            let plug_config_file = path.join(dir.rootDir, plug.url, 'src', 'config.js');

            if (!fs.existsSync(plug_config_file)) continue;
            let plug_config = require(plug_config_file)();

            for (let bean_name in plug_config.beans) {
                let bean = plug_config.beans[bean_name];
                bean.plug = name;
                (bean.tags || []).forEach(tag => {
                    if (!app.tags[tag]) app.tags[tag] = [];
                    app.tags[tag].push(bean_name);
                });
                bean.tags = null;
                app.beans[bean_name] = bean;
            }


        }

    try {
        fs.writeFileSync(app_file, "let data = " + JSON.stringify(app, null, "\t") + ";\nif (typeof window != 'undefined') window.app = data; else module.exports = data;")
    } catch (err) {
        console.error(err)
    }


};
